package com.xii.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
@Service
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    //模拟mysql
    HashMap<String, UserInfo> usermap = new HashMap<>();
    public void init() {

        usermap.put("admin",new UserInfo("admin",bCryptPasswordEncoder.encode("1234")));
        usermap.put("test",new UserInfo("test",bCryptPasswordEncoder.encode("1111")));
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        init();
        //从数据库查询用户
        UserInfo userInfo = usermap.get(username);
        if(userInfo == null){
            return null;
        }
//        String password = "{noop}"+userInfo.getPassword();
        String password = userInfo.getPassword();
        //模拟权限集合
        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if("admin".equals(username)){
            grantedAuthorities.add(new SimpleGrantedAuthority("add"));
            grantedAuthorities.add(new SimpleGrantedAuthority("delete"));
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));    //admin用户拥有ROLE_ADMIN权限
        }else{
            grantedAuthorities.add(new SimpleGrantedAuthority("add"));
        }
        return new User(username,password,grantedAuthorities);
    }

    public static void main(String[] args){
//        springsecurity的bcrypt加密算法
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode("1234");
        System.out.println("加密："+encode);
    }
}
